<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Products extends Backend {

    public function __construct()
    {
        parent::__construct();
        $this->load->model(['category_model','goods_model','site_model','job_model','sitecategory_model']);
        $this->lang->load('products');
        $this->data['page_home']  = lang('lang_dashboard');
        $this->data['page_title'] = lang('lang_productcat');
        $this->systemconfig = get_system_settings();
        $this->load->driver('cache');
    }


    private function refixtitle($title)
    {

        $mark = explode(PHP_EOL,$this->systemconfig["remove_dot"]);
        foreach($mark as &$m)
        {
            $m=trim($m);
        }
        $key = explode(PHP_EOL,$this->systemconfig["remove_keyword"]);
        foreach($key as &$k)
        {
            $k=trim($k);
        }

        $title=str_ireplace($mark,"",$title);
        $find=[];
        foreach($key as $k)
        {
            $find[]='/\b'.$k.'\b/i';
        }
        $title=preg_replace($find,"",$title);
        $title=preg_replace('/[^\w\s[:punct:]]/i','',$title);
        $title=preg_replace('/\s+/i'," ",$title);
        return ucwords(trim($title));
    }


    public function index()
    {
        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home']  => 'backend',
            $this->data['page_title'] => 'backend/products'
        );

        if(IS_POST && $this->input->post("action"))
        {
            if($this->input->post("action")=="add")
            {
                $newdata=[
                    "name"=>$this->input->post("name"),
                    "note"=>$this->input->post("note"),
                ];
                $this->category_model->create($newdata);
                redirect('backend/products', 'refresh');
                die();
            }
        }

        $page=max(1,(int) $this->input->get('page'));
        $key=trim($this->input->get('keyword'));
        $adminid=(int) $this->input->get('adminid');

        $page_data=$this->category_model->getpage($page,$key,$adminid);

        $this->data['data']=$page_data["data"];
        $this->data['pager']=$page_data["pager"];


        $keyword = array(
            'name'      => 'keyword',
            'id'        => 'keyword',
            'value'     =>  $key,
            'class'     =>  'form-control input-sm',
            'placeholder'=> '请输入关键字',
            'maxlength' => '100'
        );

        $this->data['adminid']=$adminid;
        $this->data['keyword']=$keyword;
        $this->data['adminlist']=$this->category_model->getadminlist();


        $this->data['content_header_title'] = content_header_title($this->data['page_title']);
        $this->data['content'] = 'products/category';

        $this->render();
    }



    /* 按关键词清理商品 */
    public function clean($id)
    {
        $shop=$this->category_model->getitembyid($id);
        if(empty($shop)){
            echo "错误分类不存在";
            die();
        }
        $this->data['shop']=$shop;


        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home']  => 'backend',
            $this->data['page_title'] => 'backend/products',
            "产品列表" => 'backend/products/pagelist/'.$id,
            "清理无用商品"=> 'backend/products/clean/'.$id,
        );


        $nopage=0;
        $this->form_validation->set_rules('ruler', '请输入清理规则', 'required');

        if (isset($_POST) && ! empty($_POST))
        {
            $confirm=trim($this->input->post('confirm'));
            if(empty($confirm)) $confirm=0;
            if($confirm==0)
            {
                if ($this->form_validation->run() == TRUE )
                {
                    $ruler=trim($this->input->post('ruler'));
                    $cleantype=intval($this->input->post('cleantype'));

                    $rulers=explode(PHP_EOL,$ruler);
                    foreach($rulers as $k=>$v)
                    {
                        if(empty($v))
                            unset($rulers[$k]);
                        else
                            $rulers[$k]=trim($v);
                    }
                    $products=$this->goods_model->getallgoods($id);
                    $removeids=[];
                    foreach($products as $p)
                    {
                        $f=0;
                        foreach($rulers as $r)
                        {
                            if(stristr($p["name"],$r))
                            {
                                $f=1;
                                break;
                            }
                        }
                        if($cleantype==1 && $f==0)
                        {
                            $removeids[]=$p["id"];
                        }
                        if($cleantype==2 && $f==1)
                        {
                            $removeids[]=$p["id"];
                        }

                    }

                    $this->data["ruler"]=implode(",",$rulers);
                    $this->data["total"]=count($removeids);
                    $this->data["ids"]=implode(",",$removeids);

                    $nopage=1;

                    $this->data['content'] = 'products/clean_confirm';
                    $this->clean_render();
                }

            }
            else
            {
                $ids=$this->input->post('ids');
                $id_array=preg_split('/,/',$ids);

                $this->goods_model->delitem($id_array);
                //$newdata=array("delete"=>1);
                //$this->goods_model->update($id_array, $newdata);

                $this->session->set_flashdata('message', "商品清理成功，共删除 ".count($id_array)." 条商品");
                redirect('/backend/products/clean/'.$id, 'refresh');
            }
        }


        $this->data['ruler'] = array(
            'name'  => 'ruler',
            'id'    => 'ruler',
            'type'  => 'textarea',
            'class' => 'form-control',
            'value' => "",
        );

        $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
        if($nopage==0)
        {

            $this->data['content_header_title'] = content_header_title($this->data['page_title'],"清理产品");
            $this->data['content'] = 'products/clean';
            $this->render();

        }
    }


    public function pagelist($shopid){

        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home']  => 'backend',
            $this->data['page_title'] => 'backend/products',
            "产品列表" => 'backend/products/1'
        );

        if (isset($_POST) && ! empty($_POST))
        {
            $formaction=trim($this->input->post('formaction'));
            $itemid=$this->input->post('checkItem');
            switch($formaction){
                case "delete":
                    //$notice_data=array("delete"=>1);
                    //$this->goods_model->update($itemid, $notice_data);
                    $this->goods_model->delitem($itemid);

                    break;
                case "trans":
                    $transhopid=$this->input->post('shopid');
                    $dump=$this->input->post('dump');
                    $check=$this->category_model->getitembyid($transhopid);
                    if($check)
                    {
                        if($dump==1)
                        {
                            $ids=implode(",",$itemid);
                            $goods=$this->goods_model->getallgoodsids($ids);
                            foreach($goods as $good)
                            {
                                $good["catid"]=$transhopid;
                                unset($good["id"]);
                                $this->goods_model->create($good);
                            }
                        }
                        else
                        {
                            $notice_data=array("catid"=>$transhopid);
                            $this->goods_model->update($itemid, $notice_data);
                        }
                    }
                    break;
                case "batchpush":
                    $ids=implode(",",$itemid);
                    $siteid=$this->input->post('siteid');
                    $catid=$this->input->post('catid');
                    if(empty($groupnum)) $groupnum=0;
                    $filter=["siteid"=>$siteid,"catid"=>$catid,"ids"=>$ids];

                    $newdata=[
                        "job_type"=>"batchpush",
                        "totals"=>count($itemid),
                        "filter"=>json_encode($filter),
                    ];
                    $cat = $this->category_model->getitembyid($shopid);
                    $site=$this->site_model->getitembyid($siteid);
                    $sitecategory=$this->sitecategory_model->getitembyid($catid);
                    $newdata["note"]="批量推送，产品库 <a href='/backend/products/pagelist/".$shopid."' target='_blank'>".$cat["name"]."</a>，推送店铺 <a href='/backend/sites/category/index/".$siteid."' target='_blank'>".$site["name"]."</a>,推送分类:".$sitecategory["name"];
                    $this->job_model->create($newdata);
                    break;
                case "tagging":

                    $session=$this->input->post('session');
                    $newtype=strtoupper($this->input->post('diytype'));
                    if($session || $newtype)
                    {
                        $newdata=[];
                        if($session)
                        {
                            $newdata["session"]=implode(",",$session);
                        }
                        if($newtype)
                        {
                            $newdata["collection"]=$newtype;
                            @$this->cache->redis->delete('collection'.$shopid);
                        }
                        if($newdata)
                        {
                            $this->goods_model->update($itemid, $newdata);
                        }
                    }

                    break;
                case "import":
                    break;
            }
            redirect('/backend/products/pagelist/'.$shopid, 'refresh');
        }
        $key=trim($this->input->get('keyword'));
        $page=max(1,(int) $this->input->get('page'));
        $pagesize=intval($this->input->get('pagesize'));
        if($pagesize){
            set_cookie("pagesize",$pagesize,60*60*24);
        }else{
            $pagesize=get_cookie("pagesize");
        }
        $filter=[];
        $pastday=$this->input->get("pastday");
        $sesson=$this->input->get("sesson");
        $collection=$this->input->get("collection");
        $sort=$this->input->get("sort");
        $price_min=$this->input->get("price_min");
        $price_max=$this->input->get("price_max");
        $alicategory=$this->input->get("alicategory");
        $alicategory2=$this->input->get("alicategory2");

        $push=$this->input->get("push");
        if(empty($sort)){$sort="addtime_desc";}
        if($price_min && $price_max && intval($price_min)<intval($price_max))
        {
            $filter["price_min"]=intval($price_min);
            $filter["price_max"]=intval($price_max);
        }
        else
        {
            $filter["price_min"]=$filter["price_max"]="";
        }
        $filter["sort"]=$sort;
        $filter["push"]=$push;
        $filter["alicategory"]=$alicategory;
        if(empty($alicategory) && $alicategory2)
        {
            $filter["alicategory"]=$alicategory2;
        }
        $filter["collection"]=$collection;
        $filter["pastday"]=$pastday;
        $filter["sesson"]=$sesson;
        $this->data['filter']=$filter;
        if(empty($sort)) $sort="addtime";

        $this->data['shop']= $this->category_model->getitembyid($shopid);

        $totalcount=$this->data['shop']["gcount"];
        $page_data=$this->goods_model->getpage($shopid,$page,$key,$filter,$pagesize,0,$totalcount);
        $this->data['loglist']=$page_data["data"];
        $this->data['pager']=$page_data["pager"];
        $this->data['total']=$page_data["total"];
        $this->data['pages']=$page_data["pages"];
        $this->data['page']=$page;
        $this->data['pagesize']=$pagesize;


        //if ( ! $collection = $this->cache->redis->get('collection'.$shopid))
        //{
        $collection = $this->goods_model->get_type($shopid);

        //$this->cache->redis->save('collection'.$shopid, serialize($collection), 60*60*24);
        //}
        //else
        //{
        //    $collection = unserialize($collection);
        //}
        $this->data['collection']=$collection;
        $keyword = array(
            'name'      => 'keyword',
            'id'        => 'keyword',
            'value'     =>  $key,
            'class'     =>  'form-control input-sm',
            'placeholder'=> '请输入关键字',
            'maxlength' => '100'
        );

        $myshops=$this->category_model->getall();
        foreach($myshops as $k=>$shop)
        {
            if($shop["id"]==$shopid)
            {
                unset($myshops[$k]);
            }
        }

        $config=get_system_settings();
        $alicategoey=[];
        if(isset($config["expresscategory"]) && $config["expresscategory"])
        {
            $rows=explode("\n",$config["expresscategory"]);
            if($rows)
            {
                foreach($rows as $row)
                {
                    if($row && strstr($row,"#"))
                    {
                        $tmp=explode("#",$row);
                        $alicategoey[]=["name"=>trim($tmp[0]),"ids"=>trim($tmp[1])];
                    }
                }
            }
        }
        $this->data["alicategoey"]=$alicategoey;

        $sites=$this->site_model->getallsync();
        $this->data["sites"]=$sites;

        $this->data['myshops']=$myshops;
        $this->data['keyword']=$keyword;

        $this->data['content_header_title'] = content_header_title($this->data['page_title'],"产品列表");
        $this->data['content'] = 'products/goods';

        $this->render();

    }


    //翻译属性
    public function transoption($shopid)
    {

        $this->load->model("translate_model");

        if (isset($_POST) && ! empty($_POST))
        {

            if($this->input->post("trans"))
            {
                foreach($this->input->post("trans") as $k=>$v)
                {
                    if(trim($v) && $this->input->post("from")[$k])
                    {
                        $newdata=[
                            "og"=>trim($this->input->post("from")[$k]),
                            "trans"=>trim($v),
                        ];
                        $this->translate_model->create($newdata);
                    }
                }
            }

        }


        $trans=$transg=[];
        $products=$this->goods_model->getallgoodsoption($shopid);
        foreach($products as $p)
        {
            $ooldoption=$p["option"];
            $p["option"]=unserialize($p["option"]);
            if($p["option"]["vv"])
            {
                foreach($p["option"]["vv"] as $cc=>$f)
                {
                    if(!preg_match("/^[a-zA-Z0-9()（）#\/\-\s]+$/",$f["name"]) && !isset($trans[$f['name']]))
                    {
                        $trans[$f['name']]=1;
                        $transg[$f['name']]=$p["id"];
                    }
                    foreach($f['value'] as $dd=>$v)
                    {
                        if(!preg_match("/^[a-zA-Z0-9()（）#\/\-\s]+$/",$v) && !isset($trans[$v])){
                            $trans[$v]=1;
                            $transg[$v]=$p["id"];
                        }
                    }
                }
            }
        }
        $transform=[];
        foreach($trans as $k=>$v)
        {
            $item=$this->translate_model->get_by_key($k);
            if($item)
            {
                $trans[$k]=$item["trans"];
            }
            else
            {
                $transform[]=$k;
            }
        }
        if($transform)
        {

            // Title
            $this->data['meta_title'] = $this->data['page_title'];

            // Breadcrumbs
            $this->data['array_breadcrumbs'] = array(
                $this->data['page_home']  => 'backend',
                $this->data['page_title'] => 'backend/products',
                "产品列表" => 'backend/products/pagelist/'.$shopid,
                "产品属性翻译" => 'titlerepalce/'.$shopid
            );

            $this->data["transform"]=$transform;
            $this->data["transg"]=$transg;

            $this->data['content_header_title'] = content_header_title($this->data['page_title'],"产品描述替换");
            $this->data['content'] = 'products/trans_option';
            $this->render();

        }
        else
        {
            foreach($products as $p)
            {
                $source=$p["option"];
                $p["option"]=unserialize($p["option"]);
                if($p["option"]["vv"])
                {
                    foreach($p["option"]["vv"] as $k=>$f)
                    {
                        if(isset($trans[$f['name']])) $p["option"]["vv"][$k]["name"]=$trans[$f['name']];
                        foreach($f['value'] as $j=>$v)
                        {
                            if(isset($trans[$v])) $p["option"]["vv"][$k]["value"][$j]=$trans[$v];
                        }
                    }
                }
                $newoption=serialize($p["option"]);
                if($newoption!=$source)
                {
                    $newdata=["option"=>$newoption];
                    $this->goods_model->update($p["id"],$newdata);
                }

            }

            $this->data["message"]="商品属性已经替换成功.";
            $this->data["url"]="/backend/products/pagelist/".$shopid;

            $this->data['content'] = '_template/message';
            $this->clean_render();

        }

    }



    public function descreplace($id)
    {
        $shop=$this->category_model->getitembyid($id);
        if(empty($shop)){
            echo "错误分类不存在";
            die();
        }

        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home']  => 'backend',
            $this->data['page_title'] => 'backend/products',
            "产品列表" => 'backend/products/pagelist/'.$id,
            "产品描述替换" => 'titlerepalce/'.$id
        );

        $this->data['shop']=$shop;

        $message="";
        if (isset($_POST) && ! empty($_POST))
        {
            $addtocontent=trim($this->input->post('addtocontent'));
            $desc2=$this->input->post('newdesc');

            if( $desc2 )
            {
                $where=array("catid"=>$id,"delete"=>0);
                $products=$this->goods_model->get_items_by_where_fix($where);
                foreach($products as $p)
                {

                    if($addtocontent==1)
                    {
                        $newdata["desc"]=$p["desc"].$desc2;
                    }
                    else
                    {
                        $newdata["desc"]=$desc2;
                    }


                    $this->goods_model->update($p["id"],$newdata);
                }
                $message="描述批量替换成功";
            }
            else
            {
                $message="产品描述不能为空";
            }
        }

        $this->data['message']=$message;
        $this->data['content_header_title'] = content_header_title($this->data['page_title'],"产品描述替换");
        $this->data['content'] = 'products/desc_replace';
        $this->render();

    }

    public function shopify($id){
        $shop=$this->category_model->getitembyid($id);
        if(empty($shop)){
            echo "错误目录不存在";
            die();
        }

        $checkitem=$this->input->post('checkItem');
        if($checkitem && is_array($checkitem)){
            $checkstring=implode(",",$checkitem);
        }else{
            $checkstring="";
        }
        $this->data['checkstring']=$checkstring;

        $this->data['shop']=$shop;

        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home']  => 'backend',
            $this->data['page_title'] => 'backend/products',
            "产品列表" => 'backend/products/pagelist/'.$id,
            "导出到CSV" => 'shopify/'.$id
        );

        $this->form_validation->set_rules('vendor', '请输入供应商名称', 'required');
        $this->form_validation->set_rules('prefix', '请输入SKU前缀', 'required');
        $this->form_validation->set_rules('type', '请输入导入商品分类', 'required');
        $this->form_validation->set_rules('price_muti', '请输入价格倍数', 'required');

        if (isset($_POST) && ! empty($_POST) && strstr($this->input->server("HTTP_REFERER"),"products/shopify"))
        {
            if ($id != $this->input->post('id'))
            {
                show_error('CSRF 错误，请重新操作');
            }

            if ($this->form_validation->run() == TRUE)
            {
                $vendor=$this->input->post("vendor");
                $prefix=$this->input->post("prefix");
                $type=$this->input->post("type");
                $platform=$this->input->post("platform");
                $price_muti=$this->input->post("price_muti");

                $other=$this->input->post("other");
                $filtertype=$this->input->post("filtertype");

                $this->load->library('parsecsv');
                switch($filtertype)
                {
                    case 0:
                        $ids=trim($this->input->post("ids"));
                        $products=$this->goods_model->getallgoodsids($ids);
                        break;
                    case 1:
                        $timelimit=$this->input->post("timelimit");
                        $products=$this->goods_model->getallgoods($id,$timelimit);
                        break;
                    case 2:
                        $start=intval($this->input->post("start"));
                        $end=intval($this->input->post("end"));
                        $number=$end-$start+1;
                        $from=$start-1;
                        $products=$this->goods_model->get_range($id,$from,$number);
                        break;
                    case 3:
                        $skey=trim($this->input->post("skey"));
                        $products=$this->goods_model->get_bykey($id,$skey);
                        break;
                    default:
                        die("error type");
                }

                if($products && file_exists(APPPATH."/libraries/csv/".$platform.".php")){
                    include APPPATH."/libraries/csv/".$platform.".php";
                }
                else if(!$products)
                {
                    die("没有找到商品，请重试");
                }
                else
                {
                    die("error output csv type");
                }

            }
        }


        $this->data['vendor'] = array(
            'name'  => 'vendor',
            'id'    => 'vendor',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => "",
        );
        $this->data['prefix'] = array(
            'name'  => 'prefix',
            'id'    => 'prefix',
            'type'  => 'text',
            'class' => 'form-control',
            'value' =>"",
        );

        $this->data['type'] = array(
            'name'  => 'type',
            'id'    => 'type',
            'type'  => 'text',
            'class' => 'form-control',
            'value' =>"",
        );

        $this->data['price_muti'] = array(
            'name'  => 'price_muti',
            'id'    => 'price_muti',
            'type'  => 'text',
            'class' => 'form-control',
            'value' =>"0-10:plus#10||10-15:multi#1.7||def:multi#1.9",
        );

        $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));


        $this->data['content_header_title'] = content_header_title($this->data['page_title'],"生成CSV文件");
        $this->data['content'] = 'products/shopify';
        $this->render();

    }


    public function titlereplace($id){

        $shop=$this->category_model->getitembyid($id);
        if(empty($shop)){
            echo "错误分类不存在";
            die();
        }

        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home']  => 'backend',
            $this->data['page_title'] => 'backend/products',
            "产品列表" => 'backend/products/pagelist/'.$id,
            "产品标题替换" => 'titlerepalce/'.$id
        );


        $checkitem=$this->input->get('checkItem');
        if($checkitem && is_array($checkitem)){
            $checkstring=implode(",",$checkitem);
        }else{
            $checkstring="";
        }
        $this->data['checkstring']=$checkstring;

        $this->data['shop']=$shop;

        $nopage=0;
        if (isset($_POST) && ! empty($_POST))
        {

            $size=50;
            $page=trim($this->input->post('page'));
            if(empty($page)) $page=1;

            $ruler=trim($this->input->post('ruler'));

            $replacetype=$this->input->post('replacetype');
            $replacearray=$findarray=[];
            $rulers=explode(PHP_EOL,$ruler);

            $transtitle=$this->input->post('transtitle');
            $transoption=$this->input->post('transoption');
            $cleantitle=$this->input->post('cleantitle');

            if(empty($transtitle)){
                $transtitle=$transoption="0";
            }
            if($transtitle=="0" && $transoption=="0")
            {
                $size=6000;
            }
            if($replacetype==3)
            {
                $onetitle=$this->input->post('onetitle');
                $deltitle=$this->input->post('deltitle');
                if(empty($onetitle))
                {
                    $this->session->set_flashdata('message', "统一标题不能为空");
                    redirect('backend/products/titlereplace/'.$id, 'refresh');
                }

                ini_set('memory_limit', '2G');
                $products=$this->goods_model->getpage($id,$page,'','id',$size);
                if(empty($products["data"]))
                {
                    $this->session->set_flashdata('message', "没有找到产品");
                    redirect('backend/products/titlereplace/'.$id, 'refresh');
                }

                foreach($products["data"] as $p)
                {
                    if($deltitle==1)
                    {
                        $newdata=["name"=>$p["id"]." ".$onetitle];
                    }
                    else
                    {
                        $newdata=["name"=>$p["id"]." ".$onetitle.$p["name"]];
                    }
                    $this->goods_model->update($p["id"],$newdata);
                }

                $this->session->set_flashdata('message', "标题替换成功");
                redirect('backend/products/goods/'.$id, 'refresh');


            }
            else
            {

                if($replacetype==2)
                {
                    foreach($rulers as $ruler)
                    {
                        $ruler=str_replace("\r","",$ruler);
                        if($ruler && strstr($ruler,"="))
                        {

                            $tmp=explode("=",$ruler);
                            $findarray[]=$tmp[0];
                            $replacearray[]=$tmp[1];
                        }
                        else if($ruler)
                        {
                            $findarray[]=$ruler;
                            $replacearray[]="";
                        }
                    }
                }
                else
                {
                    foreach($rulers as $ruler)
                    {
                        $ruler=str_replace("\r","",$ruler);
                        if($ruler && strstr($ruler,"==="))
                        {
                            $tmp=explode("===",$ruler);
                            $find=trim($tmp[0]);
                            $toreplace=trim($tmp[1]);
                            if(strtolower($toreplace)=="[null]")
                            {
                                $toreplace="";
                            }elseif(strtolower($toreplace)=="[whitespace]")
                            {
                                $toreplace=" ";
                            }
                            if(in_array($find,$findarray))
                            {
                                continue;
                            }
                            if(in_array(substr($find,0,1),["-","'","#"]))
                            {
                                $findarray[]='/'.$find.'\b/i';
                            }
                            else if(in_array(substr($find,-1),["-","'","#","+","!"]) || in_array(substr($find,-2),["\d"]))
                            {
                                $findarray[]='/\b'.$find.'/i';
                            }
                            else if(substr($find,0,3)=="m#m")
                            {
                                $find=str_replace("m#m","",$find);
                                $findarray[]='/'.$find.'/i';
                            }
                            else
                            {
                                $findarray[]='/\b'.$find.'\b/i';
                            }
                            $replacearray[]=$toreplace;
                        }
                    }
                }


                if($findarray || $transtitle!="0" || $transoption!="0" || $cleantitle!="0")
                {

                    ini_set('memory_limit', '2G');
                    if($transtitle!="0" || $transoption!="0")
                    {
                        $config = get_system_settings();
                        $client = new \GoogleTranslate\Client($config["apikey"]);
                    }
                    $products=$this->goods_model->getpage($id,$page,'',[],$size);
                    if(empty($products["data"]))
                    {
                        $this->session->set_flashdata('message', "产品标题替换成功");
                        redirect('backend/products/titlereplace/'.$id, 'refresh');
                    }

                    foreach($products["data"] as $p)
                    {

                        $newname=$p["name"];
                        $newdata=[];

                        if($findarray)
                        {
                            if($replacetype==2)
                            {
                                $newname=str_replace($findarray,$replacearray,$newname);
                            }
                            else
                            {
                                $newname=preg_replace($findarray,$replacearray,$newname);
                            }
                        }

                        if($transtitle!="0")
                        {
                            try
                            {
                                $newname=$client->translate($newname, $transtitle , $sourceLanguage);
                            }
                            catch (Exception $e)
                            {

                            }
                        }

                        if($transoption!="0")
                        {
                            $newoption=unserialize($p["option"]);
                            if($newoption){
                                if(isset($newoption["vv"]) && $newoption["vv"]):
                                    foreach($newoption["vv"] as $k=>$v)
                                    {
                                        try{
                                            $newoption["vv"][$k]["name"]=$client->translate($v["name"], $transoption , $sourceLanguage);
                                        }catch (Exception $e) {}
                                        foreach($v["value"] as $j=>$w)
                                        {
                                            try{
                                                $newoption["vv"][$k]["value"][$j]=$client->translate($w, $transoption , $sourceLanguage);
                                            }catch (Exception $e) {}
                                        }
                                    }
                                endif;
                            }
                            $newoption=serialize($newoption);
                            if($newoption!=$p["option"])
                            {
                                $newdata["option"]=$newoption;
                            }
                        }
                        if($cleantitle==1)
                        {
                            $newname=$this->refixtitle($newname);
                        }
                        if($newname!=$p["name"])
                        {
                            $newname=trim(preg_replace('/\s+/i'," ",$newname));
                            $newdata["name"]=$newname;
                        }

                        if($newdata && $newdata["name"])
                        {
                            if(empty($p["oname"]) && isset($newdata["name"]))
                            {
                                $newdata["oname"]=$p["name"];
                            }
                            $this->goods_model->update($p["id"],$newdata);
                        }

                    }
                    $this->data['ruler']=$ruler;
                    $this->data['page']=$page+1;
                    $this->data['replacetype']=$replacetype;
                    $this->data['transtitle']=$transtitle;
                    $this->data['transoption']=$transoption;
                    $this->data['cleantitle']=$cleantitle;
                    $nopage=1;
                    $this->data['content'] = 'products/replace_continue';
                    $this->clean_render();
                }
            }
        }

        $this->data['ruler'] = array(
            'name'  => 'ruler',
            'id'    => 'ruler',
            'type'  => 'textarea',
            'class' => 'form-control',
            'value' => "",
        );

        $pagetype=$this->input->get('pagetype');
        $this->data['pagetype']=$pagetype;



        $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
        if($nopage==0)
        {
            $this->data['content_header_title'] = content_header_title($this->data['page_title'],"产品标题替换");
            $this->data['content'] = 'products/title_replace';
            $this->render();
        }

    }


    //更新产品图
    public function updateimage()
    {
        $config = $this->systemconfig_model->get_configs();
        $gid=$this->input->post("goodid");
        $org=$this->input->post("org");
        $newurl=$this->input->post("newurl");

        $good=$this->goods_model->getbyid($gid);
        if($good)
        {
            $thumb=unserialize($good["thumb"]);
            foreach($thumb as &$img)
            {
                if(strstr($img,$config["urlpath"]))
                {
                    continue;
                }
                foreach($org as $k=>$v)
                {
                    if($img==$v)
                    {
                        $img=$newurl[$k];
                    }
                }
            }
            $newdata=["thumb"=>serialize($thumb)];
            $option=unserialize($good["option"]);
            if($option && isset($option["vv"][0]["image"]))
            {
                foreach($option["vv"][0]["image"] as &$opimg)
                {
                    if(strstr($opimg,$config["urlpath"]))
                    {
                        continue;
                    }
                    foreach($org as $k=>$v)
                    {
                        if($opimg==$v)
                        {
                            $opimg=$newurl[$k];
                        }
                    }
                }
                $newdata["option"]=serialize($option);
            }
            $this->goods_model->update($good["id"],$newdata);
        }
        echo json_encode([]);
        die();
    }

    //编辑产品
    public function editgoods($goodsid){

        $this->data['goods']=$this->goods_model->getbyid($goodsid);

        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        $catid=$this->input->get("catid");
        $this->data["catid"]=$catid;
        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home']  => 'backend',
            $this->data['page_title'] => 'backend/products',
            "产品列表" => 'backend/products/pagelist/'.($this->data['goods']?$this->data['goods']["catid"]:$catid),
            $this->data['goods']?"编辑产品".$this->data['goods']["name"]:"添加产品"=> 'editgood'
        );

        $this->form_validation->set_rules('name', '产品名称', 'required');
        $this->form_validation->set_rules('price', '产品价格', 'required');
        $this->form_validation->set_rules('desc', '产品描述', 'required');

        if (isset($_POST) && ! empty($_POST))
        {
            if ($goodsid != $this->input->post('id'))
                //if ($this->_valid_csrf_nonce() === FALSE OR $goodsid != $this->input->post('id'))
            {
                show_error('CSRF 错误，请重新操作');
            }
            if ($this->form_validation->run() == TRUE)
            {

                $thumb=$this->input->post("thumb");
                $desc2=$this->input->post('newdesc');
                if($desc2)
                {
                    $preg = "/<\s*[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/i";
                    preg_match_all($preg, $desc2, $allImg);
                    if(isset($allImg[1]) && $allImg[1]){
                        foreach($allImg[1] as $img){
                            $thumb[]=$img;
                        }
                    }
                }

                $prooption = unserialize($this->data['goods']['option']);


                $updata=array(
                    "thumb"=>serialize($thumb),
                    "name" => $this->input->post('name'),
                    "price" => $this->input->post('price'),
                    "desc" => $this->input->post('desc'),
                    "edittime"=>date("Y-m-d H:i:s"),
                );


                $optionname=$this->input->post("optionname");
                $optionimg=$this->input->post("optionimg");
                $optionval=$this->input->post("optionval");
                $optionprice=$this->input->post("optionprice");

                if($optionname)
                {
                    $option=[];
                    foreach($optionname as $k=>$v)
                    {
                        $newoption=[
                            "name"=>$v,
                            "value"=>$optionval[$k]
                        ];
                        if(isset($optionimg[$k]) && $optionimg[$k])
                        {
                            $newoption["image"]=$optionimg[$k];
                        }
                        if(isset($optionprice[$k]) && $optionprice[$k])
                        {
                            $newoption["price"]=$optionprice[$k];
                        }
                        $allempty=true;
                        foreach($optionprice[$k] as $p)
                        {
                            if(!empty($p))
                            {
                                $allempty=false;
                                break;
                            }
                        }
                        if($allempty)
                        {
                            unset($newoption["price"]);
                        }
                        $option[]=$newoption;
                    }
                    $prooption["vv"]=$option;
                    $updata["option"]=serialize($prooption);
                }

                if($goodsid==0)
                {
                    $updata["source"]="后台添加";
                    $updata["source_url"]="#";
                    $updata["tbid"]="0";
                    $updata["catid"]=$this->input->post("catid");
                    $this->goods_model->create($updata);
                    redirect('backend/products/pagelist/'.$updata["catid"], 'refresh');
                    die();
                }
                else
                {
                    if($this->goods_model->update($goodsid, $updata))
                    {
                        redirect('backend/products/editgoods/'.$this->data['goods']["id"], 'refresh');
                        die();
                        echo "产品更新成功。<script>window.close()</script>";
                        die();
                        $this->session->set_flashdata('message', $this->goods_model->messages());
                        redirect('admin/tbshop/goods/'.$this->data['goods']["catid"], 'refresh');
                        die();
                    }
                }
            }

        }


        $this->data['gname'] = array(
            'name'  => 'name',
            'id'    => 'name',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->data["goods"]['name'],
        );
        $this->data['gprice'] = array(
            'name'  => 'price',
            'id'    => 'price',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->data["goods"]['price'],
        );

        $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));

        $this->data['content_header_title'] = content_header_title($this->data['page_title'],"编辑产品");
        $this->data['content'] = 'products/editgood';

        $this->render();

    }


    public function ajaxskupriceedit()
    {
        $return=["status"=>0,"msg"=>"失败"];
        $gid=$this->input->post("gid");
        $skuval=$this->input->post("skuval");
        $skuprice=$this->input->post("skuprice");
        $product=$this->goods_model->getbyid($gid);
        if(!$product)
        {
            $return["msg"]="记录不存在";
        }
        else
        {
            $newsku=[];
            if($skuval):
                foreach($skuval as $k=>$v)
                {
                    $tmp=["val"=>[],"price"=>0];
                    $tmp["val"]=explode("::",$v);
                    foreach($tmp["val"] as &$vv)
                    {
                        $vv=trim($vv);
                    }
                    if(isset($skuprice[$k]))
                    {
                        $tmp["price"]=floatval($skuprice[$k]);
                    }
                    $newsku[]=$tmp;
                }
            endif;
            $option=unserialize($product["option"]);
            $option["newsku"]=$newsku;
            $newdata=["option"=>serialize($option)];
            $this->goods_model->update($gid,$newdata);
            $return["msg"]="变体价格更新成功";
            $return["status"]=1;
        }
        echo json_encode($return,JSON_UNESCAPED_UNICODE);
        die();
    }

    public function goodsajaxdel()
    {
        $return=["status"=>1];
        $cid=$this->input->post("cid");
        if(!$this->goods_model->delitem($cid))
        {
            $return["status"]=0;
            $return["msg"]="删除失败";
        }
        echo json_encode($return);
        die();
    }

    public function ajaxcatedit()
    {
        $attrName=$this->input->post("attrName");
        $newHtml=$this->input->post("newHtml");
        $cid=$this->input->post("cid");
        $newdata[$attrName]=$newHtml;
        $this->category_model->update($cid, $newdata);
        echo json_encode([]);
        die();
    }
    public function goodsajaxedit()
    {
        $attrName=$this->input->post("attrName");
        $newHtml=$this->input->post("newHtml");
        $cid=$this->input->post("cid");
        $newdata[$attrName]=$newHtml;
        $this->goods_model->update($cid, $newdata);
        echo json_encode([]);
        die();
    }

    public function categoryajaxdel()
    {

        $return=["status"=>1];
        $cid=$this->input->post("cid");
        if(!$this->category_model->delete($cid))
        {
            $return["status"]=0;
            $return["msg"]="删除失败";
        }

        echo json_encode($return);
        die();
    }


    public function categoryajaxedit()
    {

        $attrName=$this->input->post("attrName");
        $newHtml=$this->input->post("newHtml");
        $cid=$this->input->post("cid");
        $newdata[$attrName]=$newHtml;
        $this->category_model->update($cid, $newdata);
        echo json_encode([]);
        die();
    }

}